package com.xyy.kingdeejdy.helper;

import com.alibaba.fastjson.JSON;
import com.smecloud.apigw.client.ApigwClient;
import com.smecloud.apigw.constant.HttpMethod;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import com.xyy.kingdeejdy.pojo.erp.help.JdyResult;
import com.xyy.kingdeejdy.utils.TokenCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author itmei
 * @Date 2023/7/29 12:02
 * @description: 金蝶HTTP请求封装
 * @Title: JdApi
 * @Package com.xyy.kingdeejdy.helper
 */
@Slf4j
public class JdApi {
    private static final int MAX_RETRY_COUNT = 5;

    public static <T> JdyResult saveApi(HttpMethod method, String url, List<T> data) {
        if (data.isEmpty()) {
            log.info("导入信息为空!!!! data: {}", data);
            return new JdyResult<>();
        }
        String jsonData = JSON.toJSONString(data);
        ApiRequest request = new ApiRequest(method, "api.kingdee.com", url);
        Map<String, String> map = new HashMap<>();
        map.put("access_token", TokenCache.getToken());
        map.put("dbId", "796392012921816");
        request.setQuerys(map);
        Map<String, String> map1 = new HashMap<>();
        map1.put("items", jsonData);
        byte[] jsonBytes = JSON.toJSONBytes(map1);
        request.setBodyJson(jsonBytes);
        ApiResult send = ApigwClient.getInstance().send(request);
        if (send == null && send.getHttpCode() != 0) {
            log.warn("导入金蝶信息失败!!! jsonData: {} param:{}", JSON.toJSONString(send), jsonData);
            return new JdyResult();
        }
        JdyResult jdyResult = JSON.parseObject(send.getBody(), JdyResult.class);
        return jdyResult;
    }

    public static <T> JdyResult quersyApi(HttpMethod method, String url, T data) {
        String jsonData = JSON.toJSONString(data);
        ApiRequest apiRequest = new ApiRequest(method, "api.kingdee.com", url);
        Map<String, String> map = new HashMap<>();
        map.put("access_token", TokenCache.getToken());
        map.put("dbId", "796392012921816");
        apiRequest.setQuerys(map);
        Map<String, String> file = new HashMap<>();
        file.put("filter", jsonData);
        byte[] jsonBytes = JSON.toJSONBytes(file);
        apiRequest.setBodyJson(jsonBytes);
        ApiResult send = ApigwClient.getInstance().send(apiRequest);
        if (send == null && send.getHttpCode() != 0) {
            log.warn("查询金蝶信息失败!!! jsonData: {} param:{}", JSON.toJSONString(send), jsonData);
            return new JdyResult();
        }
        JdyResult jdyResult = JSON.parseObject(send.getBody(), JdyResult.class);
        return jdyResult;
    }
}
